package com.hmall.service;

import com.hdmall.business.common.common.ServerResponse;
import com.hmall.mapper.*;
import com.hmall.model.*;
import com.hmall.util.EnvUtil;
import com.hdmall.business.common.util.HttpClientUtil;
import com.hdmall.business.common.util.JsonUtils;
import com.hdmall.business.common.util.NumberUtil;
import com.hmall.vo.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.IOException;
import java.io.StringReader;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author zhoutao
 */
@Service
public class MallProductPlanService {


    private MallProductPlanMapper mallProductPlanMapper;

    private MallProductPlanItemMapper mallProductPlanItemMapper;

    private MallProductMapper mallProductMapper;

    private MallPriceMapper mallPriceMapper;

    private MallDealerMapper mallDealerMapper;

    private SysUserMapper sysUserMapper;

    private MallAttrConnectMapper mallAttrConnectMapper;

    private SysDeptCustomerMapper sysDeptCustomerMapper;

    private SysCustomerMapper sysCustomerMapper;

    private MallShopMapper mallShopMapper;

    private MallProductPlanTimeMapper mallProductPlanTimeMapper;

    private EnvUtil envUtil = new EnvUtil();

    @Autowired
    public MallProductPlanService(MallAttrConnectMapper mallAttrConnectMapper, MallProductPlanMapper mallProductPlanMapper, MallProductPlanItemMapper mallProductPlanItemMapper, MallProductMapper mallProductMapper, MallProductPlanTimeMapper mallProductPlanTimeMapper, MallPriceMapper mallPriceMapper, MallDealerMapper mallDealerMapper, SysUserMapper sysUserMapper, MallShopMapper mallShopMapper, SysDeptCustomerMapper sysDeptCustomerMapper, SysCustomerMapper sysCustomerMapper) {
        this.mallAttrConnectMapper = mallAttrConnectMapper;
        this.mallProductPlanMapper = mallProductPlanMapper;
        this.mallProductPlanItemMapper = mallProductPlanItemMapper;
        this.mallProductMapper = mallProductMapper;
        this.mallProductPlanTimeMapper = mallProductPlanTimeMapper;
        this.mallPriceMapper = mallPriceMapper;
        this.mallDealerMapper = mallDealerMapper;
        this.sysUserMapper = sysUserMapper;
        this.mallShopMapper = mallShopMapper;
        this.sysDeptCustomerMapper = sysDeptCustomerMapper;
        this.sysCustomerMapper = sysCustomerMapper;
    }


    /**
     * @Date 2018/11/9 14:49
     * @Param [userId, productListJsonStr, remark, submitPerson]
     * @return com.hmall.common.ServerResponse
     * @Description //
     * 一个公司生产计划只有一个
     */
    public ServerResponse createProductPlan(Integer userId, String productListJsonStr,  String remark,Integer submitPerson) {


        //对于用户来说只有生产计划状态为未审核才能进行修改
//         String testStr = "[{\"amount\":10,\"grade\":\"AA不定重\",\"productId\":518,\"weight\":10}]";
//        productListJsonStr = testStr;
        List<ProductAndPriceVo> productAndPriceVoList = JsonUtils.jsonToList(productListJsonStr, ProductAndPriceVo.class);

        //1表示未审核
        int status = 0;
        if(2 == submitPerson) {
            status = 1;
        }

        //1号00:00:00 到 23号23:59:59可以申请
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = sdf.format(date);
        int year = Integer.valueOf(dateStr.split("-")[0]);
        int month = Integer.valueOf(dateStr.split("-")[1]);
        int day = Integer.valueOf(dateStr.split("-")[2]);

        //24号00:00:00到每个月的月底不能申请
        //业务员可以进行申请，直接变成审核通过

        boolean check = (day >= 1 && day <= 23 && submitPerson == 1) || submitPerson == 2;
        if (check) {
            //暂时审核通过，不考虑工作流
         //   if(submitPerson == 2) status = 2;


            //根据用户找到用户的公司的创建计划的那个人
            Integer customerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(userId);
            Integer createCustomerUserId = sysCustomerMapper.selectCustomerUserId(customerId);

            //找到他所绑定的办事处

            SysCustomer customer = sysCustomerMapper.selectByUserId(createCustomerUserId);
            Integer dealerId = customer.getDealerId();
            Integer salesId = customer.getSalesmanId();

            Calendar calendar = Calendar.getInstance();
            calendar.set(year, month - 1, 1, 0, 0, 0);
            calendar.set(Calendar.MILLISECOND, 0);

            Date startDate = calendar.getTime();
            calendar.set(year, month , 1, 0, 0, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            Date endDate = calendar.getTime();

            MallProductPlan mallProductPlan = mallProductPlanMapper.selectThisMonthPlan(startDate, endDate, createCustomerUserId);
            //2018.9.12改版为所有月份传PlanId
            if(submitPerson == 1 && mallProductPlan.getStatus() != 0){
                return ServerResponse.createByErrorMessage("当前月份的计划单已经通过，无法再次创建");
            }

                   Integer planId = mallProductPlan.getPlanId();
                    mallProductPlanMapper.myUpdate(planId, createCustomerUserId, remark, status, dealerId, salesId, submitPerson);
                    //根据planNo先把子的都删了（简便，不判重复选择更新）
                    mallProductPlanItemMapper.batchDelete(mallProductPlan.getPlanNo());
                    //同插入
                    for (ProductAndPriceVo productAndPriceVo : productAndPriceVoList) {
                        mallProductPlanItemMapper.myInsert(mallProductPlan.getPlanNo(), productAndPriceVo.getProductId(), productAndPriceVo.getGrade(), productAndPriceVo.getAmount(), productAndPriceVo.getAmount());
                    }
                    //更新索引
                    MallProductPlan mallProductPlanIndex = mallProductPlanMapper.selectByPlanNo(mallProductPlan.getPlanNo());
                    updateIndex(mallProductPlanIndex);
                }
         else {
            return ServerResponse.createByErrorMessage("已超过申请时间，请在以下时间段申请 1号00:00:00——23号23:59:59");
        }

        //先进行查询操作，如果已经下的计划时间段在上个月的24:00:24号00:00:00到
        return ServerResponse.createBySuccess("创建成功");
    }

    private Map<String, String> preIndex(MallProductPlan mallProductPlan) {


        Map<String, String> map = new HashMap<>();
        map.put("id", mallProductPlan.getPlanId().toString());
        map.put("deal_way", mallProductPlan.getDealWay());
        map.put("remark", mallProductPlan.getRemark());

        map.put("create_time", mallProductPlan.getCreateTime().toString());
        String statusStr = "";
        switch (mallProductPlan.getStatus()) {
            case 0: {
                statusStr = "未审核";
                break;
            }
            case 1: {
                statusStr = "审核中";
                break;
            }
            case 2: {
                statusStr = "通过";
                break;
            }
            case 3: {
                statusStr = "未通过";
                break;
            }
            default:{
                break;
            }
        }
        map.put("status", statusStr);
        String salesmanName = sysUserMapper.selectByPrimaryKey(mallProductPlan.getSaleUserId()).getUsername();
        map.put("salesmanName", salesmanName);
        map.put("plan_no", mallProductPlan.getPlanNo().toString());
        map.put("opinion", mallProductPlan.getOpinion());

        String username = sysUserMapper.selectByPrimaryKey(mallProductPlan.getUserId()).getUsername();
        map.put("username", username);
        List<MallProductPlanItemVo> mallProductPlanItemVoList = new ArrayList<>();
        List<MallProductPlanItem> mallProductPlanItemList = mallProductPlanItemMapper.listProductPlanItemByPlanNo(mallProductPlan.getPlanNo());
        for (MallProductPlanItem mallProductPlanItem : mallProductPlanItemList) {
            int productId = mallProductPlanItem.getProductId();
            MallProduct mallProduct = mallProductMapper.selectByPrimaryKey(productId);
            mallProductPlanItemVoList.add(new MallProductPlanItemVo(mallProductPlanItem.getAmount(), mallProductPlanItem.getGrade(), mallProduct.getName()));
        }
        map.put("productList", mallProductPlanItemVoList.toString());
        return map;
    }


    /**
     * @Date 2018/11/9 14:52
     * @Param [mallProductPlan]
     * @return void
     * @Description // 更新索引
     */
    private void updateIndex( MallProductPlan mallProductPlan) {

        Map<String, String> map = preIndex(mallProductPlan);

        String s = HttpClientUtil.doPostWithParam("http://47.98.171.71:8081/hdfind/updatePlan", map);
//        String s = HttpClientUtil.doPostWithParam("http://192.168.21.7:8081/hdfind/updatePlan", map);
    }


    public ServerResponse<PageVo<MallProductPlanVo>> listProductPlan(Integer userId, Integer status, Integer pageNum, Integer pageSize) {

        boolean check = !(status != null && (status == 1 || status == 2 || status == 3 || status == 4 || status == 5 || status == 6));
        if (check) {
            return ServerResponse.createByErrorMessage("请输入正确的状态");
        }

        //现在生产计划是公司的
        //根据userId找到那个人
        Integer customerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(userId);
        Integer createUserId = sysCustomerMapper.selectCustomerUserId(customerId);
        List<MallProductPlan> mallProductPlanList = mallProductPlanMapper.listProductPlan(createUserId);


        List<MallProductPlanVo> mallProductPlanVoList = new ArrayList<>();

        for (MallProductPlan mallProductPlan : mallProductPlanList) {

            Integer mallProductPlanItemCount = mallProductPlanItemMapper.selectCountByProductPlanNo(mallProductPlan.getPlanNo());
            if(mallProductPlanItemCount == 0) {
                continue;
            }
            //指定类型
            List<Integer> productIdList = mallProductPlanItemMapper.selectByPlanNo(mallProductPlan.getPlanNo());
            System.out.println(productIdList);
            List<String> nameList = mallProductMapper.selectNameByProductIdList(productIdList);

            String type;
            Set<String> set = new HashSet<>();
            for (String str : nameList) {
                type = str.substring(0, 3);
                set.add(type);
            }

            List<String> typeList = new ArrayList<>(set);

            //1 全部 2 审核中 3.通过 4.不通过 5.未审核 6.已失效

            //数据库
            //0 未审核  1 正在审核处理  2 审核通过 3 未通过 4.已失效

            MallProductPlanVo mallProductPlanVo = new MallProductPlanVo(mallProductPlan.getPlanId(), mallProductPlan.getStatus(), typeList, mallProductPlan.getCreateTime());

            //写得不好
            if (status == 1) {
                mallProductPlanVoList.add(mallProductPlanVo);
            } else if (status == 2 && mallProductPlan.getStatus() == 1) {
                mallProductPlanVoList.add(mallProductPlanVo);
            } else if (status == 3 && mallProductPlan.getStatus() == 2) {
                mallProductPlanVoList.add(mallProductPlanVo);
            } else if (status == 4 && mallProductPlan.getStatus() == 3) {
                mallProductPlanVoList.add(mallProductPlanVo);
            } else if (status == 5 && mallProductPlan.getStatus() == 0) {
                mallProductPlanVoList.add(mallProductPlanVo);
            } else if (status == 6 && mallProductPlan.getStatus() == 4) {
                mallProductPlanVoList.add(mallProductPlanVo);
            }

        }
        int total = mallProductPlanVoList.size();
        int realPageNum = (pageNum - 1) * pageSize;

        List<MallProductPlanVo> subMallProductPlanVo = mallProductPlanVoList.subList(realPageNum, Math.min(realPageNum + pageSize, total));

        PageVo<MallProductPlanVo> pageVo = new PageVo<>(pageNum, pageSize, total, subMallProductPlanVo);

        return ServerResponse.createBySuccess(pageVo);
    }

    public ServerResponse<MallProductPlanDetialListVo> listProductPlanDetial(int planId) {

        //没必要，一对一，现在懒得改
        MallProductPlan mallProductPlan = mallProductPlanMapper.selectByPrimaryKey(planId);
        if (mallProductPlan == null) {
            return ServerResponse.createByErrorMessage("请输入正确的计划编号");
        }
        Long planNo = mallProductPlan.getPlanNo();

        List<MallProductPlanItem> mallProductPlanItemList = mallProductPlanItemMapper.listProductPlanItemByPlanNo(planNo);


        MallProductPlanDetialListVo mallProductPlanDetialListVo = new MallProductPlanDetialListVo();

        //如果本计划单是上个月提交的并且审核通过，表示可以下单
        Calendar calendar = Calendar.getInstance();
        Integer month = calendar.get(Calendar.MONTH);
        Integer year = calendar.get(Calendar.YEAR);
        calendar.set(year, month - 1, 1, 0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date startDate = calendar.getTime();
        calendar.set(year, month, 1, 0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date endDate = calendar.getTime();
        //满足上个月提交的并且审核通过
        if(mallProductPlan.getCreateTime().getTime() >= startDate.getTime() && mallProductPlan.getCreateTime().getTime() <= endDate.getTime() && mallProductPlan.getStatus() == 2) {
            mallProductPlanDetialListVo.setOrderCheck(1);
        }

        List<MallProductPlanDetialVo> list = new ArrayList<>();
        //总重量
        BigDecimal weight = new BigDecimal(0.0);
        for (MallProductPlanItem mallProductPlanItem : mallProductPlanItemList) {

            int productId = mallProductPlanItem.getProductId();
            String grade = mallProductPlanItem.getGrade();
            BigDecimal amount = mallProductPlanItem.getAmount();

            weight = weight.add(mallProductPlanItem.getAmount());
            String name = mallProductMapper.selectNameByProductId(productId);
            name +=  grade + ",";
            String []nameStr = name.split(",", -1);
            String type = nameStr[0];
            String unit = "(dtex/f)";
            String fineAndPoreStr = nameStr[3] + nameStr[4] + unit;
            String model = nameStr[2];
            String attr = nameStr[1] + "-" + nameStr[5] + "-" + nameStr[6] + "-" + nameStr[7] +
                    "-" + nameStr[8] + "-" + nameStr[9];

            MallProductPlanDetialVo mallProductPlanDetialVo = new MallProductPlanDetialVo(productId, name, amount, type, grade, attr, fineAndPoreStr, model);
            mallProductPlanDetialVo.setImg(mallProductMapper.selectByPrimaryKey(productId).getMainImage().split(",")[0]);


            mallProductPlanDetialVo.setResidualQuantity(mallProductPlanItem.getResidualQuantity());
            mallProductPlanDetialVo.setPlanItemId(mallProductPlanItem.getPlanItemId());
            list.add(mallProductPlanDetialVo);
        }
            Integer saleUserId = mallProductPlanMapper.selectSaleUserIdByPlanId(planId);
            SysUser user = sysUserMapper.selectByPrimaryKey(saleUserId);
            String saleManName;
            String saleManPhone;
            if (user == null) {
                saleManName = "默认名称";
                saleManPhone = "默认手机号";
            }else {
                saleManName = user.getRealName();
                saleManPhone = user.getPhone();
            }
            mallProductPlanDetialListVo.setMallProductPlanDetialVo(list);
            mallProductPlanDetialListVo.setSalesManName(saleManName);
            mallProductPlanDetialListVo.setPhoneNumber(saleManPhone);
            mallProductPlanDetialListVo.setWeight(weight);
            int status = mallProductPlanMapper.selectStatusByPlanId(planId);

            mallProductPlanDetialListVo.setStatus(status);

            String remark = mallProductPlanMapper.selectRemarkByPlanId(planId);
            mallProductPlanDetialListVo.setRemark(remark);
            mallProductPlanDetialListVo.setPlanId(planId);

        return ServerResponse.createBySuccess(mallProductPlanDetialListVo);

    }


    /**
     * @Date 2018/11/9 14:54
     * @Param [userId]
     * @return com.hmall.common.ServerResponse
     * @Description //
     * user表里面 dept_id代表办事员和用户绑定
     *     dealer表示 该用户与办事处绑定
     *     user_dept 是资质的表
     */
    public ServerResponse listAllSalesMan(Integer userId) {

        //1.先找到该用户绑定的dealerId
        // 2.根据dealerId找下面的与该办事处绑定的user_id
        SysUser user = sysUserMapper.selectByPrimaryKey(userId);
        //用户绑定的办事处的id
        int dealerId = user.getDealerId();
        //根据绑定的办事处的dealerId 找到deptId
        Integer deptId = mallDealerMapper.selectDeptIdByDealerId(dealerId);
        //根据deptId 找到user_id集合
        List<Integer> userIdList = sysUserMapper.selectUserIdListByDeptId(deptId);
        //根据deptId 找到用户的username 和这个question(后台是用作名称)

        List<SysUser> saleUserList;
        if (userIdList.size() != 0) {
            saleUserList = sysUserMapper.selectSaleManByUserIdList(userIdList);
            return ServerResponse.createBySuccess(saleUserList);
        } else {
            return ServerResponse.createByErrorMessage("该办事处下暂无业务员");
        }
    }

    public ServerResponse updatePlanToDo() {

        //定时任务更新计划,只推送一次
        MallProductPlanTime mallProductPlanTime = mallProductPlanTimeMapper.selectAll().get(0);
        Calendar calendar = Calendar.getInstance();

        //一分钟内把计划状态从待审核到审核中
        if(calendar.get(Calendar.DATE) == mallProductPlanTime.getDay() && calendar.get(Calendar.HOUR) == mallProductPlanTime.getHour() && calendar.get(Calendar.MINUTE) == 0){
            mallProductPlanMapper.updatePlanToDo(calendar.getTime());
        }
        return null;

    }

    public ServerResponse updatePlanToInvalid() {

        Calendar calendar = Calendar.getInstance();
        Integer thisYear = calendar.get(Calendar.YEAR);
        Integer thisMonth = calendar.get(Calendar.MONTH);
        calendar.set(thisYear, thisMonth - 1, 1, 0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date nowDate = calendar.getTime();

        //比当前时间早的计划
        mallProductPlanMapper.updatePlanStatusOverTime(nowDate);

        calendar.set(Calendar.MONTH, thisMonth);
        Date thisDate = calendar.getTime();
        List<MallProductPlan> mallProductPlanList = mallProductPlanMapper.selectByTime(nowDate, thisDate);
        for(MallProductPlan  mallProductPlan: mallProductPlanList){
            //如果没有计划产品或者状态不为审核通过
            if(mallProductPlanItemMapper.selectCountByProductPlanNo(mallProductPlan.getPlanNo()) == 0 || mallProductPlan.getStatus() != 2){
                mallProductPlanMapper.updatePlan(mallProductPlan.getPlanId(), 4);
            }
        }
        return ServerResponse.createBySuccess();
    }

    public ServerResponse getProductPlanDetail(Integer userId, Integer planId) {


        if (planId != null) {
            MallProductPlan mallProductPlan = mallProductPlanMapper.selectByPrimaryKey(planId);
            if (mallProductPlan == null) {
                return ServerResponse.createByErrorMessage("该计划单号不存在");
            }
            return listProductPlanDetial(planId);

        }
        //要返回当前月份的planId
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        Integer tYear = calendar.get(Calendar.YEAR);
        Integer tMonth = calendar.get(Calendar.MONTH);
        calendar.set(tYear, tMonth, 1, 0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date startDate = calendar.getTime();
        calendar.set(tYear, tMonth + 1, 1, 0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date endDate = calendar.getTime();
        Integer customerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(userId);

        Integer createUserId = sysCustomerMapper.selectCustomerUserId(customerId);


        MallProductPlan mallProductPlan = mallProductPlanMapper.selectThisMonthPlan(startDate, endDate, createUserId);
        //未审核的
        Integer mallProductPlanItemCount = mallProductPlanItemMapper.selectCountByProductPlanNo(mallProductPlan.getPlanNo());
        if (mallProductPlan.getStatus() == 0 && mallProductPlanItemCount!= 0) {
            return listProductPlanDetial(mallProductPlan.getPlanId());
        } else {
           return  ServerResponse.createBySuccessMessage("暂无当月未审核的生产计划");
        }
    }

    /**
     * @Date 2018/11/9 14:56
     * @Param [subModel, shopId, searchCount]
     * @return com.hmall.common.ServerResponse<java.util.List<java.lang.String>>
     * @Description //
     * 根据子批号查询出<=15条的批号信息
     * mysql默认查询不区分大小写
     */
    public ServerResponse<List<String>> getModelListList(String subModel, Integer shopId, Integer searchCount) {
        List<String> tModelList = mallAttrConnectMapper.selectLikeModel(subModel, shopId, searchCount);

        List<String> modelList = new ArrayList<>();
        Set<String> set = new HashSet<>(tModelList);
        tModelList.clear();
        tModelList.addAll(set);
        for(String model : tModelList){
            String str = model + "-";
            List<MallProduct> mallProductList = mallProductMapper.selectAllByModel(model);
            for(MallProduct mallProduct : mallProductList){
                String twisting = mallProduct.getName().split(",", -1)[9];
                String newStr = str;
                if(!"".equals(twisting)) {
                    newStr += twisting + "-";
                }
                List<MallPrice> mallPriceList = mallPriceMapper.selectByProductId(mallProduct.getId());
                for(MallPrice mallPrice : mallPriceList){
                    modelList.add(newStr + mallPrice.getGrade());

                }
            }
        }
        return ServerResponse.createBySuccess(modelList);
    }

    public ServerResponse<ProductAndGradeVo> getProductInformationByModel(String model) {


        String []args = model.split("-", -1);

        if (args.length != 2 && args.length != 3) {
            return ServerResponse.createByErrorMessage("请输入正确的产品信息");
        }
        MallProduct mallProduct;
        //如果没有捻度这一项
        if(args.length == 2){
            mallProduct = mallProductMapper.selectByModel(args[0]);
        }else{
            mallProduct = mallProductMapper.selectByModelAndTwisting(args[0], args[1]);
        }


        ProductAndGradeVo productAndGradeVo = new ProductAndGradeVo();
        if (mallProduct == null) {
            return ServerResponse.createByErrorMessage("找不到该产品，请重新输入批号");
        }
        List<String> grade = mallPriceMapper.selectGradeList(mallProduct.getId());
        productAndGradeVo.setGrade(grade);
        productAndGradeVo.setMallProduct(mallProduct);
        return ServerResponse.createBySuccess(productAndGradeVo);
    }

    public ServerResponse<String> printPlanOrder(String jsonStr, String remark) {


        //转换json
        JSONArray jsonArray = JSONArray.fromObject(jsonStr);
        List<JsonPrintVo> jsonPrintVoList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JsonPrintVo jsonPrintVo = (JsonPrintVo) JSONObject.toBean((JSONObject) jsonArray.get(i), JsonPrintVo.class);
            jsonPrintVoList.add(jsonPrintVo);
        }
        Iterator<JsonPrintVo> iterator = jsonPrintVoList.iterator();
        List<ProductPlanOrderVo> productPlanOrderVoList = new ArrayList<>();

        Integer totalWeight = 0;

        while (iterator.hasNext()) {
            JsonPrintVo jsonPrintVo = iterator.next();
            int productId = jsonPrintVo.getProductId();
            String grade = jsonPrintVo.getGrade();
            Integer weight = jsonPrintVo.getWeight();
            String name;
            try {
                name = mallProductMapper.selectByProductId(productId).getName();
            } catch (Exception e) {
                return ServerResponse.createByErrorMessage("请输入正确的批号");
            }
            totalWeight += weight;
            String []attrStr = name.split(",", -1);
            String type = attrStr[0];
            String gloss = attrStr[1];
            String model = attrStr[2];
            String findAndPore = attrStr[3] + attrStr[4];
            String singleShare = attrStr[5];
            String color = attrStr[6];
            String section = attrStr[7];
            String netWork = attrStr[8];
            String twisting = attrStr[9];
            ProductPlanOrderVo productPlanOrderVo = new ProductPlanOrderVo(type, model, findAndPore, grade, color, gloss, singleShare, section, twisting, netWork, weight);
            productPlanOrderVoList.add(productPlanOrderVo);
        }

        PrintProductVo printProductVo = new PrintProductVo();
        printProductVo.setProductPlanOrderVoList(productPlanOrderVoList);
        printProductVo.setRemark(remark);
        printProductVo.setTotalWeigth(totalWeight);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = sdf.format(new Date());
        printProductVo.setDate(dateStr);


        String month = dateStr.split("-")[1];
        //pdf名称命名规则
        String name = month + "月计划表";
        printProductVo.setName(name);

        String planStr = JsonUtils.objectToJsonStr(printProductVo);
        Map<String, String> map = new HashMap<>();
        map.put("planStr", planStr);
        String url = envUtil.getPreUrl("order");
        url += "/pdf/showProductPlanPdf";
        String s = HttpClientUtil.doGetWithParam(url, map);
        return ServerResponse.createBySuccess(s);
    }

    public ServerResponse<List<MallProductPlanVo>> productPlanSearch(Integer userId, String keywords) throws IOException {

        //得到planId的集合
        List<MallProductPlan> mallProductPlanList = new ArrayList<>();

        //如果未传入东西，直接返回全部数据
        //如果传入数据，返回搜索出来的数据
        if (keywords == null || "".equals(keywords)) {
            mallProductPlanList = mallProductPlanMapper.listAllPlanListByUser(userId);
        } else {
            //请求索引获取planId列表
            Analyzer analyzer = new IKAnalyzer(false);
            StringReader reader = new StringReader(keywords);
            TokenStream ts = analyzer.tokenStream("", reader);
            ts.reset();
            CharTermAttribute term = ts.getAttribute(CharTermAttribute.class);
            StringBuilder str = new StringBuilder();
            while (ts.incrementToken()) {
                System.out.println(term.toString() + "|");
                str.append(term.toString()).append(",");
            }


            analyzer.close();
            reader.close();
            Map<String, String> map = new HashMap<>();
            String username = sysUserMapper.selectByPrimaryKey(userId).getUsername();

            map.put("username", username);
            map.put("query", str.toString());
            //调用索引

            //唯一
            String s = HttpClientUtil.doGetWithParam("http://47.98.171.71:8081/hdfind/findPlan", map);

            List<String> parentPlanIdList = Arrays.asList(s.split(","));
            List<String> planIdList = parentPlanIdList.subList(1, parentPlanIdList.size());


            //根据productId的列表查找plan的属性
            List<Integer> planIdListInt = new ArrayList<>();
            for (Object i : planIdList) {
                int planId = Integer.parseInt((String) i);
                planIdListInt.add(planId);
            }
            Collections.sort(planIdListInt);


            if (planIdList.size() != 0) {
                mallProductPlanList = mallProductPlanMapper.listProductPlanByPlanIdList(planIdListInt);
            }
        }

        List<MallProductPlanVo> mallProductPlanVoList = new ArrayList<>();

        for (MallProductPlan mallProductPlan : mallProductPlanList) {
            //指定类型
            List<Integer> productIdList = mallProductPlanItemMapper.selectByPlanNo(mallProductPlan.getPlanNo());
           if(productIdList.size() == 0) {
               continue;
           }
            List<String> nameList = mallProductMapper.selectNameByProductIdList(productIdList);
            String type;
            Set<String> set = new HashSet<>();
            for (String subName : nameList) {
                type = subName.substring(0, 3);
                set.add(type);
            }
            List<String> typeList = new ArrayList<>(set);

            //自定义头
            String title;
            Date date = mallProductPlan.getCreateTime();
            date.toLocaleString();

            //well
            //假如当前是9月 month = 9
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(mallProductPlan.getCreateTime());
            int month = calendar.get(Calendar.MONTH) + 2;

            title = month + "月计划单";
            MallProductPlanVo mallProductPlanVo = new MallProductPlanVo(mallProductPlan.getPlanId(), mallProductPlan.getStatus(), typeList, title, mallProductPlan.getPlanNo(), mallProductPlan.getCreateTime());
            mallProductPlanVoList.add(mallProductPlanVo);
        }
        return ServerResponse.createBySuccess(mallProductPlanVoList);

    }


    /**
     * @Date 2018/11/9 14:58
     * @Param [userId]
     * @return com.hmall.common.ServerResponse
     * @Description //
     * 判断当前用户当月是否可以进行生产计划
     */
    public ServerResponse checkDoPlan(Integer userId) {

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        Integer tYear = calendar.get(Calendar.YEAR);
        Integer tMonth = calendar.get(Calendar.MONTH);
        calendar.set(tYear, tMonth - 1, 1, 0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date startDate = calendar.getTime();
        calendar.set(tYear, tMonth, 1, 0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date endDate = calendar.getTime();

        Integer customerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(userId);
        Integer createUserId = sysCustomerMapper.selectCustomerUserId(customerId);

        MallProductPlan mallProductPlan = mallProductPlanMapper.selectThisMonthPlan(startDate, endDate, createUserId);
        //有模板肯定不为空
        if(mallProductPlan.getStatus() == 0){
            return ServerResponse.createBySuccessMessage("可以进行生产计划编辑");
        }

        if(mallProductPlan.getStatus() == 1){
            return ServerResponse.createByErrorMessage("您本月生产计划正在审核中");
        }

        if(mallProductPlan.getStatus() == 2){
            return ServerResponse.createByErrorMessage("您本月生产计划已通过");
        }

        if(mallProductPlan.getStatus() == 5){
            return ServerResponse.createByErrorMessage("您本月生产计划正在审核中!");
        }

        //被拒绝的生产计划还能进行提交
        return ServerResponse.createBySuccessMessage("可以进行生产计划编辑!");
    }

    /**
     * @Date 2018/11/9 14:58
     * @Param [userId, year, month]
     * @return com.hmall.common.ServerResponse<java.util.List<com.hmall.vo.ProductPlanVo>>
     * @Description // 如果当前是九月，查找上个月的计划，8月1日到9月1日
     */
    public ServerResponse<List<ProductPlanVo>> getLastMonthProductPlan(Integer userId, Integer year, Integer month) {

        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, 1, 0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date startDate = calendar.getTime();
        calendar.set(year, month, 1, 0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date endDate = calendar.getTime();
        Date startDate2 = calendar.getTime();
        calendar.set(year, month + 1, 1, 0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date endDate2 = calendar.getTime();

        Integer customerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(userId);
        Integer createUserId = sysCustomerMapper.selectCustomerUserId(customerId);

        Date[] start = {startDate, startDate2};
        Date[] end = {endDate, endDate2};
        Integer[] fMonth = {month, month + 1};
        List<ProductPlanVo> productPlanVoList = new ArrayList<>();

        //2018/10/29 改成上个月的
        for(int i = 0; i <= 0; i++) {
            MallProductPlan mallProductPlan = mallProductPlanMapper.selectThisMonthPlan(start[i], end[i], createUserId);

            //如果不是通过的不显示
            if(mallProductPlan.getStatus() != 2) {
                continue;
            }

            ProductPlanVo productPlanVo = new ProductPlanVo();

            //设置月份
            productPlanVo.setMonth(fMonth[i]);

            //设置计划编号
            productPlanVo.setPlanNo(mallProductPlan.getPlanNo());

            List<ProductPlanDetialVo> productPlanDetialVoList = new ArrayList<>();
            List<MallProductPlanItem> mallProductPlanItemList = mallProductPlanItemMapper.listProductPlanItemByPlanNo(mallProductPlan.getPlanNo());
            for (MallProductPlanItem mallProductPlanItem : mallProductPlanItemList) {
                ProductPlanDetialVo productPlanDetialVo = new ProductPlanDetialVo();
                Integer productId = mallProductPlanItem.getProductId();
                MallProduct mallProduct = mallProductMapper.selectByProductId(productId);
                String name = mallProduct.getName();
                String []nameStr = name.split(",", -1);
                productPlanDetialVo.setFineAndPore(nameStr[3] + nameStr[4]);
                productPlanDetialVo.setGrade(mallProductPlanItem.getGrade());
                BigDecimal weight = new BigDecimal(0.0);
                if( mallProductPlanItem.getResidualQuantity() != null){
                    weight = mallProductPlanItem.getResidualQuantity();
                }
                productPlanDetialVo.setWeight(weight);
                productPlanDetialVo.setImg(mallProduct.getMainImage().split(",")[0]);
                productPlanDetialVo.setModel(nameStr[2]);
                productPlanDetialVo.setProductId(mallProduct.getId());

                //下单依据
                productPlanDetialVo.setPlanItemId(mallProductPlanItem.getPlanItemId());

                productPlanDetialVo.setName(mallProduct.getName());
                String shopName = mallShopMapper.selectByPrimaryKey(mallProduct.getShopId()).getShopName();
                productPlanDetialVo.setShopName(shopName);
                productPlanDetialVoList.add(productPlanDetialVo);
            }
            productPlanVo.setProductPlanDetialVoList(productPlanDetialVoList);

            productPlanVoList.add(productPlanVo);
        }
        return ServerResponse.createBySuccess(productPlanVoList);
    }


    public ServerResponse createProductPlanByUser(Integer userId, String productListJsonStr, Integer planId, String remark, Integer submitPerson) {

        Integer BACK_FLAG = 2, FRONT_FLAG = 1;
        //对于用户来说只有生产计划状态为未审核才能进行修改

//        String testStr = "[{\"amount\":41,\"grade\":\"AA定重\",\"productId\":748}]";
//         String testStr = "[{\"amount\":10,\"grade\":\"AA不定重\",\"productId\":518,\"weight\":10}]";

//        productListJsonStr = testStr;

        List<ProductAndPriceVo> productAndPriceVoList = JsonUtils.jsonToList(productListJsonStr, ProductAndPriceVo.class);

        //1表示未审核
        int status = 0;

        //1号00:00:00 到 23号23:59:59可以申请
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = sdf.format(date);
        int year = Integer.valueOf(dateStr.split("-")[0]);
        int month = Integer.valueOf(dateStr.split("-")[1]);
        int day = Integer.valueOf(dateStr.split("-")[2]);

        //24号00:00:00到每个月的月底不能申请
        //业务员可以进行申请，直接变成审核通过

        //下下下的几个月都能进行编辑
        int flag = 0;

        if(null != planId) {
            MallProductPlan tMallProductPlan = mallProductPlanMapper.selectByPrimaryKey(planId);
            if (tMallProductPlan.getCreateTime().getTime() - date.getTime() >= 0) {
                flag = 1;
            }
        }


        boolean check = (day >= 1 && day <= 23 && submitPerson == 1) || submitPerson == 2 || flag == 1;
        if(check) {
            //暂时审核通过，不考虑工作流
            if(submitPerson.equals(BACK_FLAG)) {
                status = 2;
            }
            //根据用户找到用户的公司的创建计划的那个人
            Integer customerId = sysDeptCustomerMapper.selectCustomerIdByCustomerUserId(userId);
            Integer createCustomerUserId = sysCustomerMapper.selectCustomerUserId(customerId);

            //找到他所绑定的办事处

            SysCustomer customer = sysCustomerMapper.selectByUserId(createCustomerUserId);
            Integer dealerId = customer.getDealerId();
            Integer salesId = customer.getSalesmanId();

            Calendar calendar = Calendar.getInstance();
            calendar.set(year, month - 1, 1, 0, 0, 0);
            calendar.set(Calendar.MILLISECOND, 0);

            Date startDate = calendar.getTime();
            calendar.set(year, month , 1, 0, 0, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            Date endDate = calendar.getTime();

            //如果不传递planId说明是当月的，否则是制定月份的
            MallProductPlan mallProductPlan;
            if(planId == null){
                mallProductPlan = mallProductPlanMapper.selectThisMonthPlan(startDate, endDate, createCustomerUserId);
            }
            //2018.9.12改版为所有月份传PlanId
            else {
                mallProductPlan = mallProductPlanMapper.selectByPrimaryKey(planId);
            }
            if(submitPerson.equals(FRONT_FLAG) && mallProductPlan.getStatus() != 0){
                return ServerResponse.createByErrorMessage("当前月份的计划单已经通过，无法再次创建");
            }

            if(submitPerson.equals(BACK_FLAG) && mallProductPlan.getStatus() == 2){
                return ServerResponse.createByErrorMessage("您已经为该用户通过了一份计划单，无法再次创建");
            }

            mallProductPlanMapper.myUpdate(planId, createCustomerUserId, remark, status, dealerId, salesId, submitPerson);
            //根据planNo先把子的都删了（简便，不判重复选择更新）
            mallProductPlanItemMapper.batchDelete(mallProductPlan.getPlanNo());
            //同插入
            for (ProductAndPriceVo productAndPriceVo : productAndPriceVoList) {
                mallProductPlanItemMapper.myInsert(mallProductPlan.getPlanNo(), productAndPriceVo.getProductId(), productAndPriceVo.getGrade(), productAndPriceVo.getAmount(), productAndPriceVo.getAmount());
            }
            //更新索引
            MallProductPlan mallProductPlanIndex = mallProductPlanMapper.selectByPlanNo(mallProductPlan.getPlanNo());
            updateIndex(mallProductPlanIndex);
        }
        else {
            return ServerResponse.createByErrorMessage("已超过申请时间，请在以下时间段申请 1号00:00:00——23号23:59:59");
        }

        //先进行查询操作，如果已经下的计划时间段在上个月的24:00:24号00:00:00到
        return ServerResponse.createBySuccess("创建成功");

    }

    /**
     * @Date 2019/1/10 13:16
     * @Param []
     * @return com.hmall.common.ServerResponse
     * @Description 创建一年的计划
     */
    public ServerResponse createYearPlan() {

        List<SysCustomer> customerList = sysCustomerMapper.selectAll();
        //要判断是否该公司已经创建了计划
        for(SysCustomer customer: customerList){
            Integer userId = sysCustomerMapper.selectCustomerUserId(customer.getCustomerId());
            if(customer.getCustomerId() == 71){
                System.out.println("1");
            }
            if(userId == null) {
                continue;
            }

            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.DAY_OF_MONTH,1);
            calendar.set(Calendar.HOUR_OF_DAY,0);
            calendar.set(Calendar.MINUTE,0);
            calendar.set(Calendar.SECOND,0);
            calendar.set(Calendar.MILLISECOND, 0);
            for(int i = 1; i <= 12; i++){
                calendar.set(Calendar.MONTH, i-1);
                //当前月份如果已经有了计划不要再次创建
                Date leftTime = calendar.getTime();
                calendar.add(Calendar.MONTH, 1);
                Date rightTime = calendar.getTime();
                int count = mallProductPlanMapper.selectCountByUserIdWithTime(userId, leftTime, rightTime);
                //还原calendar

                if(count != 0) {
                    continue;
                }
                if(count >= 2){
                    //删除到只剩下一个
                    List<MallProductPlan> mallProductPlanList = mallProductPlanMapper.selectByUserIdWithTime(userId, leftTime, rightTime);
                    int num = 0;
                    for(MallProductPlan mallProductPlan : mallProductPlanList){
                        if(num == 0){
                            num = 1;
                            continue;
                        }
                        mallProductPlanMapper.deleteByPrimaryKey(mallProductPlan.getPlanId());
                    }
                }

                calendar.add(Calendar.MONTH, -1);
                createPlan(customer,calendar.getTime(), userId);

            }
        }
        return ServerResponse.createBySuccess();
    }

    private void createPlan(SysCustomer sysCustomer, Date createTime, Integer userId) {
        //获得该客户绑定的业务员
        Integer saleUserId = sysCustomer.getSalesmanId();
        //获得办事处id
        Integer dealerId = sysCustomer.getDealerId();
        //生成计划编号
        Long planNo = NumberUtil.createPlanNo(dealerId);

        Integer status = 0;
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH)-1);
        if (createTime.before(calendar.getTime())){
            status = 4;
        }
        //新建计划
        MallProductPlan mallProductPlan = new MallProductPlan();
        mallProductPlan.setUserId(userId);
        mallProductPlan.setSaleUserId(saleUserId);
        mallProductPlan.setCreateTime(createTime);
        mallProductPlan.setStatus(status);
        mallProductPlan.setDealerId(dealerId);
        mallProductPlan.setSubmitPerson(1);
        mallProductPlan.setPlanNo(planNo);

        mallProductPlanMapper.insert(mallProductPlan);
        return;
    }


}
